<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\api\controller;
use app\common\controller\Api;
use app\common\controller\Smscm;
use app\common\helper\FormatHelper;
use app\common\model\Discount;
use app\common\model\Factor;
use app\common\model\Fenorder;
use app\common\model\HandCard as HandCardM;
use app\common\model\Sms;
use app\common\service\CommonService;
use app\common\service\FuYouPayService;
use app\common\service\PrintService;
use app\common\service\RoomCheckOutService;
use app\common\service\RoomCostService;
use app\common\service\VoiceService;
use app\web\controller\Express;
use Carbon\Carbon;
use think\Db;
use app\common\service\FeiEPrintService;

/**
 * 房间结账控制器
 * @package app\index\controller
 */
class RoomCheckOut extends Auth
{
    public $noNeedLogin = [];


    /**
     * 获取用户房间结账列表
     */
    public function check_out()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $margeRoomData = '';
            $margeHandCardData = '';
            //房间ID合并
            if(isset($getData['room_id']) && !empty($getData['room_id'])){
                $margeRoomData = Db::name('qt_room')->where('id', $getData['room_id'])->value('marge');
            }
            //手牌号合并
            if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                $margeHandCardData = Db::name('qt_hand_grant')
                    ->alias('grant')
                    ->leftJoin('qt_hand_card card','card.id = grant.hand_card_id')
                    ->where(['card.name'=>$getData['hand_card_name'],'grant.status'=>'2','grant.store_id'=>$this->userInfo['store_id']])
                    ->value('marge');
            }
            //房间号合并
            if(isset($getData['room_name']) && !empty($getData['room_name'])){
                $roomId = Db::name('qt_room')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['room_name']])->value('id');
                $margeRoomData = Db::name('qt_room')->where('id', $roomId)->value('marge');
            }
            if (!empty($margeRoomData) || !empty($margeHandCardData)) {
                //有合并房间
                if($margeRoomData != ''){
                    $margeRoomID = explode(',', $margeRoomData);
                }else{
                    $margeRoomID = null;
                }
                if($margeHandCardData != ''){
                    $margeHandCard = explode(',', $margeHandCardData);
                    $handCardId = Db::name('qt_hand_grant')->whereIn('id',$margeHandCard)->column('hand_card_id');
                    $margeHandCard = $handCardId;
                }else{
                    $margeHandCard = null;
                }
                $sql =   Db::name('qt_order_project')
                    ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,room_id,hand_card_id,order_id')
                    ->whereNotNull('engineer_id')
                    ->where('engineer_id','neq','0')
                    ->where(['is_change'=>'1','pay_status'=>'0','is_delete'=>2]);
                if($margeRoomID != null ){
                    $sql->whereIn('room_id',$margeRoomID);
                }
                if($margeHandCard != null){
                    $sql->whereIn('hand_card_id',$margeHandCard);
                }
                $projectRes = $sql->select();
                foreach ($projectRes as $key => $value) {
                    $projectRes[$key]['type'] = 'project';
                    $projectRes[$key]['order_id'] = $value['order_id'];
                    $projectRes[$key]['activity_price'] = $value['price'];
                    $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                    $projectRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                }
                if($margeRoomID != null){
                    //插入房费
                    foreach ($margeRoomID as $k => $room_id) {
                        $room_data = Db::name('qt_room')->where('id', $room_id)->find();
                        RoomCostService::saveCostOrder($room_data['store_id'], $room_id, $this->userInfo);
                    }
                }
                $goodsSql = Db::name('qt_product_order_item')
                    ->field('id as product_order_id,hand_card_id,old_card_id,goods_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,order_id,sale_id,business_type,room_id')
                    ->where('pay_status', '0')
                    ->where(['status'=>'1']);
                if($margeRoomID != null){
                    $goodsSql->whereIn('room_id',$margeRoomID);
                }
                if($margeHandCard != null){
                    $goodsSql->whereIn('hand_card_id',$margeHandCard);
                }
                $productRes = $goodsSql->select();
                foreach ($productRes as $key => $value) {
                    $productRes[$key]['type'] = 'goods';
                    $productRes[$key]['project_id'] =$value['goods_id'];
                    $productRes[$key]['activity_price'] = $value['goods_price'];
                    $productRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');
                    $productRes[$key]['room_name'] = Db::name('qt_room')->where('id',$value['room_id'])->value('name');
                    $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
                    $productRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                    $productRes[$key]['old_hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['old_card_id'])->value('name');
                }
                $packageOriginal = array_merge($projectRes,$productRes);
                //处理组装原始数据

                $packageProjectData = [];
                $packageGoodsData = [];
                foreach ($packageOriginal as $key=>$value){
                    if($value['type'] == 'project'){
                        if (isset($packageProjectData[$value['project_id']])) {

                            $packageProjectData[$value['project_id']]['number'] += 1;
                        }else {
                            $packageProjectData[$value['project_id']] = $value;
                            $packageProjectData[$value['project_id']]['number'] = 1;
                        }
                    }elseif($value['type'] == 'goods'){
                        if (isset($packageGoodsData[$value['goods_id']])) {

                            $packageGoodsData[$value['goods_id']]['number'] += $value['goods_num'];
                        }else {
                            $packageGoodsData[$value['goods_id']] = $value;
                            $packageGoodsData[$value['goods_id']]['number'] = $value['goods_num'];
                        }
                    }
                }
                $packageOriginalData = array_merge($packageGoodsData,$packageProjectData);

                //查询所有套餐
                $packageSql = Db::name('qt_data_package')
                    ->field('id,name,price')
                    ->where(['store_id'=>$this->userInfo['store_id']])
                    ->select();
                foreach ($packageSql as $key=>$value){
                    $packageSql[$key]['list'] = Db::name('qt_data_package_item')
                        ->field('id,package_id,item_id as project_id,item_type as type,number')
                        ->where(['package_id'=>$value['id']])
                        ->select();
                }

                $packageSql = CommonService::useTaoCan($packageSql,$packageOriginalData);
                $data['package'] = $packageSql;
                $data['project'] = $projectRes;
                $data['goods'] = $productRes;
                $data['project_new'] = CommonService::decGoodsData($projectRes,$packageSql,'project');
                $data['project_new'] = array_values($data['project_new']);
                $data['goods_new'] = CommonService::decGoodsData($productRes,$packageSql,'goods');
                $data['goods_new'] = array_values($data['goods_new']);
                $this->result('请求成功', $data, 200);
            } else {
                $where = false;
                //单个房间项目
                $sql = Db::name('qt_order_project')
                    ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,order_id,room_id,hand_card_id')
                    ->where('is_change', '1')
                    ->where('pay_status', '0')
                    ->where('is_delete',2)
                    ->where('engineer_id','neq', '0')
                    ->whereNotNull('engineer_id');
                //房间号筛选
                if(isset($getData['room_id']) && !empty($getData['room_id'])){
                    $sql->where('room_id',$getData['room_id']);
                    $where = true;
                }
                //房间号筛选
                if(isset($getData['room_name']) && !empty($getData['room_name'])){
                    $roomId = Db::name('qt_room')->where(['name'=>$getData['room_name'],'store_id'=>$this->userInfo['store_id']])->value('id');
                    if($roomId != null){
                        $where = true;
                    }
                    $sql->where('room_id',$roomId);

                }
                //手牌筛选
                if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                    $handCardId = Db::name('qt_hand_card')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card_name']])->value('id');
                    if($handCardId != null){
                        $where = true;
                    }
                    $sql->where('hand_card_id',$handCardId);
                }
                //技师号筛选
                if(isset($getData['work_number']) && !empty($getData['work_number'])){
                    $engineerId = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'work_number'=>$getData['work_number']])->value('id');
                    if($engineerId != null){
                        $where = true;
                    }
                    $sql->where('engineer_id',$engineerId);
                }
                if($where == true){
                    $projectRes = $sql->select();
                }else{
                    $projectRes = [];
                }
                foreach ($projectRes as $key => $value) {
                    $projectRes[$key]['type'] = 'project';
                    $projectRes[$key]['order_id'] = $value['order_id'];
                    $projectRes[$key]['activity_price'] = $value['price'];
                    $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                    $projectRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                }
                //插入房费
                $room_data = Db::name('qt_room')->where('id', $getData['room_id'])->find();
                RoomCostService::saveCostOrder($room_data['store_id'], $getData['room_id'], $this->userInfo);
                //商品
                $goodsWhere = false;
                $goodsSql = Db::name('qt_product_order_item')
                    ->field('id as product_order_id,goods_id,room_id,hand_card_id,old_card_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,business_type,order_id,sale_id')
                    ->where('pay_status', '0')
                    ->where(['status'=>'1']);
                //房间号筛选
                if(isset($getData['room_id']) && !empty($getData['room_id'])){
                    $goodsSql->where('room_id',$getData['room_id']);
                    $goodsWhere = true;
                }
                //房间号筛选
                if(isset($getData['room_name']) && !empty($getData['room_name'])){
                    $roomId = Db::name('qt_room')->where(['name'=>$getData['room_name'],'store_id'=>$this->userInfo['store_id']])->value('id');
                    if($roomId != null){
                        $goodsWhere = true;
                    }
                    $goodsSql->where('room_id',$roomId);

                }
                //手牌筛选
                if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                    $handCardId = Db::name('qt_hand_card')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card_name']])->value('id');
                    if($handCardId != null){
                        $goodsWhere = true;
                    }
                    $goodsSql->where('hand_card_id',$handCardId);
                }
                //技师号筛选
                if(isset($getData['work_number']) && !empty($getData['work_number'])){
                    $engineerId = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'work_number'=>$getData['work_number']])->value('id');
                    $goodsSql->where('sale_id',$engineerId);
                    if($engineerId != null){
                        $goodsWhere = true;
                    }
                }
                if($goodsWhere == true){
                    $productRes = $goodsSql->select();
                }else{
                    $productRes = [];
                }
                foreach ($productRes as $key => $value) {
                    $productRes[$key]['type'] = 'goods';
                    $productRes[$key]['project_id'] =$value['goods_id'];
                    $productRes[$key]['activity_price'] = $value['goods_price'];
                    $productRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');
                    $productRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
                    $productRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                    $productRes[$key]['old_hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['old_card_id'])->value('name');
                }
                $packageOriginal = array_merge($projectRes,$productRes);

                $packageProjectData = [];
                $packageGoodsData = [];
                foreach ($packageOriginal as $key=>$value){
                    if($value['type'] == 'project'){
                        if (isset($packageProjectData[$value['project_id']])) {

                            $packageProjectData[$value['project_id']]['number'] += 1;
                        }else {
                            $packageProjectData[$value['project_id']] = $value;
                            $packageProjectData[$value['project_id']]['number'] = 1;
                        }
                    }elseif($value['type'] == 'goods'){
                        if (isset($packageGoodsData[$value['goods_id']])) {

                            $packageGoodsData[$value['goods_id']]['number'] += $value['goods_num'];
                        }else {
                            $packageGoodsData[$value['goods_id']] = $value;
                            $packageGoodsData[$value['goods_id']]['number'] = $value['goods_num'];
                        }
                    }
                }
                $packageOriginalData = array_merge($packageGoodsData,$packageProjectData);

                $packageSql = Db::name('qt_data_package')
                    ->field('id,name,price')
                    ->where(['store_id'=>$this->userInfo['store_id']])
                    ->select();
                foreach ($packageSql as $key=>$value){
                    $packageSql[$key]['list'] = Db::name('qt_data_package_item')
                        ->field('id,package_id,item_id as project_id,item_type as type,number')
                        ->where(['package_id'=>$value['id']])
                        ->select();
                }
                $packageSql = CommonService::useTaoCan($packageSql,$packageOriginalData);
                $data['package'] = $packageSql;
                $data['project'] = $projectRes;
                $data['goods'] = $productRes;
                $data['project_new'] = CommonService::decGoodsData($projectRes,$packageSql,'project');
                $data['project_new'] = array_values($data['project_new']);
                $data['goods_new'] = CommonService::decGoodsData($productRes,$packageSql,'goods');
                $data['goods_new'] = array_values($data['goods_new']);
                $this->result('请求成功', $data, 200);
            }
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 获取用户房间结账支付
     */
    public function pay()
    {

        if ($this->request->isPost()) {
            $post = $this->request->post();
            $filed_arr = [
                'viper_card_id','viper_card_money','project_order_total_id','goods_order_total_id',
                'content','activity_id','cashier_remarks','pay_content','engineer_ids','project_ids'
            ];
            foreach ($filed_arr as $key => $val){
                if (!isset($post[$val])) {
                    $post[$val] = '';
                }
            }
            $projectOrderIds = [];
            $goodsOrderIds = [];
            $roomIds = explode(',',$post['room_id']);
            if(isset($post['hand_card_ids']) && !empty($post['hand_card_ids'])){
                $handCardIds = explode(',',$post['hand_card_ids']);
            }else{
                $handCardIds = [];
            }
            $room_log = Db::name('qt_room_log')
                ->whereIn('room_id', $roomIds)
                ->order('id desc')->find();
            $room_status = Db::name('qt_room')
                ->whereIn('id', $roomIds)
                ->column('status_id');
            $room_status = implode(',',$room_status);
            try{
                $checkOutId = Db::name('qt_check_out')->insertGetId([
                    'store_id' => $this->userInfo['store_id'],
                    'room_id' => $post['room_id'],
                    'engineer_ids' => $post['engineer_ids'],
                    'project_ids' => $post['project_ids'],
                    'order_no' => check_order_sn(),
                    'project_order' => $post['project_order_total_id'],
                    'goods_order' => $post['goods_order_total_id'],
                    'viper_card_id' => $post['viper_card_id'],
                    'viper_card_money' => $post['viper_card_money'],
                    'total_money' => $post['total_money'],
                    'payment_money' => $post['payment_money'],
                    'cashier_id' => $this->userInfo['id'],
                    'cashier_time' => time(),
                    'activity_id' => $post['activity_id'],
                    'cashier_remarks' => $post['cashier_remarks'],
                    'pay_content' => $post['pay_content'],
                    'open_room_time' => $room_log['created_time'],
                    'room_status'=>$room_status
                ]);
                check_out_pay_all($post['pay_content'], $checkOutId, $this->userInfo, '2');
                //会员卡结算 card_pay_type 1 会员卡余额 2 次卡 3 月卡
                if (isset($post['card_data']) && !empty($post['card_data'])) {
                    $cardData = json_decode($post['card_data'], true);
                    foreach ($cardData as $key => $value) {
                        //会员次卡结账
                        if ($value['card_pay_type'] == '2') {
                            $pay_num_card = RoomCheckOutService::payNumberCard($value, $checkOutId);
                            if (!empty($pay_num_card['code']) && $pay_num_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_num_card['msg'], '', 204);
                            }

                            $pay_card = RoomCheckOutService::payCard($value, $checkOutId,$this->userInfo);
                            if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_card['msg'], '', 204);
                            }
                        } elseif ($value['card_pay_type'] == '3') {
                            //会员月卡结账
                            $pay_month_card = RoomCheckOutService::payMonthCard($value, $checkOutId);
                            if (!empty($pay_month_card['code']) && $pay_month_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_month_card['msg'], '', 204);
                            }
                            $pay_card = RoomCheckOutService::payCard($value, $checkOutId,$this->userInfo);
                            if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_card['msg'], '', 204);
                            }
                        } elseif ($value['card_pay_type'] == '1') {
                            //会员卡结账
                            $pay_card = RoomCheckOutService::payCard($value, $checkOutId,$this->userInfo);
                            if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                                $this->result($pay_card['msg'], '', 204);
                            }
                        }
                    }
                }
                //项目计算
                $projectRes = json_decode($post['project'], true);
                $totalProjectPrice = 0;
                $projectInsert = [];
                if (!empty($projectRes)) {
                    foreach ($projectRes as $key => $value) {
                        $projectInsert[$key] = [
                            'activity_id' => $post['activity_id'],
                            'link_id' => $value['project_id'],
                            'link_type' => '1',
                            'link_order_id' => $value['project_order_id'],
                            'check_out_id' => $checkOutId,
                            'receivable' => $value['payment_price'] ?? $value['price'],
                            'actual_receipt' => $value['activity_price'] ?? $value['price'],
                            'total_num' => 1,
                            'deduction_price' => $value['payment_price'] - $value['activity_price'],
                            'create_time'=>time()
                        ];
                        $totalProjectPrice += $value['payment_price'];
                        if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                            $value['is_discount'] = 0;
                        }
                        if(!empty($value['activity_price'])){
                            $payment = $value['activity_price'];
                        }else{
                            $payment =$value['payment_price'];
                        }
                        Db::name('qt_order_project')->where('id', $value['project_order_id'])->update([
                            'payment_price' => $payment,
                            'is_discount' => $value['is_discount'],
                            'pay_status' => '1',
                            'pay_time' => time()
                        ]);
                        //如果有手牌减手牌金额
                        $projectOrderData = Db::name('qt_order_project')->where('is_delete',2)->where('id', $value['project_order_id'])->find();
                        if(!empty($projectOrderData['hand_card_id'])){
                            $handGrand = Db::name('qt_hand_grant')
                                ->where(['hand_card_id'=>$projectOrderData['hand_card_id'],'status'=>'2'])
                                ->order('id desc')
                                ->find();
                            Db::name('qt_hand_grant')->where(['id'=>$handGrand])->setDec('money',$value['price']);
                        }
                        //更新提成记录时间
                        Db::name('qt_commission_log')
                            ->where(['order_project_id' => $value['project_order_id'], 'type' => '1'])
                            ->update(['updated_time' => time(),'payment_price'=>$payment]);
                        $projectOrderIds[$key] = $value['project_order_id'];
                    }
                    //更新详情订单号
                    Db::name('qt_order_detail')->whereIn('order_project_id',$projectOrderIds)->update(['check_out_id'=>$checkOutId]);
                }
                //商品数据插入
                $totalGoodsPrice = 0;
                $goodsInsert = [];
                $goodsRes = json_decode($post['goods'], true);
                if (!empty($goodsRes)) {
                    foreach ($goodsRes as $key => $value) {
                        $goodsInsert[$key] = [
                            'activity_id' => $post['activity_id'],
                            'link_id' => $value['goods_id'],
                            'link_type' => '2',
                            'link_order_id' => $value['product_order_id'],
                            'check_out_id' => $checkOutId,
                            'receivable' => bcmul($value['payment_price'],$value['goods_num'],1)  ?? bcmul($value['goods_total_price'],$value['goods_num'],1),
                            'actual_receipt' => bcmul($value['activity_price'] ,$value['goods_num'],1) ?? bcmul($value['goods_total_price'],$value['goods_num'],1),
                            'total_num' => $value['goods_num'],
                            'deduction_price' => bcsub($value['payment_price'],$value['activity_price']),
                            'create_time'=>time()
                        ];
                        $totalGoodsPrice += intval($value['payment_price']);
                        if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                            $value['is_discount'] = 0;
                        }
                        if(!empty($value['activity_price'])){
                            $payment = $value['activity_price'];
                        }else{
                            $payment =$value['payment_price'];
                        }
                        Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->update([
                            'payment_price' => $payment * $value['goods_num'],
                            'is_discount' => $value['is_discount'],
                            'pay_status' => '1',
                            'pay_time'=>time()
                        ]);
                        //如果有手牌减手牌金额
                        $goodsOrderData = Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->find();
                        if(!empty($goodsOrderData['hand_card_id'])){
                            $handGrand = Db::name('qt_hand_grant')
                                ->where(['hand_card_id'=>$goodsOrderData['hand_card_id'],'status'=>'2'])
                                ->order('id desc')
                                ->find();
                            Db::name('qt_hand_grant')->where(['id'=>$handGrand])->setDec('money',$value['goods_total_price']);
                        }
                        //更新提成记录时间
                        Db::name('qt_commission_log')
                            ->where(['order_project_id' => $value['product_order_id'], 'type' => '2'])
                            ->update(['updated_time' => time(),'payment_price'=>$payment]);
                        $goodsOrderIds[$key] = $value['product_order_id'];
                    }
                    Db::name('qt_order_detail')->whereIn('order_goods_id',$goodsOrderIds)->update(['check_out_id'=>$checkOutId]);
                }
                //查询技师是否在房间内
                if(!empty($roomIds)){
                    foreach ($roomIds as $key=>$value){
                        $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $value])->find();
                        //如果技师没在房间内，更新总项目订单的状态
                        if (empty($engineerStatus)) {
                            foreach ($projectOrderIds as $k=>$v){
                                //判断房间是否还有未结账的项目子订单如果没有更新总订单
                                $checkProjectOrder = Db::name('qt_order_project')
                                    ->where([ 'pay_status' => '0'])
                                    ->where('is_delete',2)
                                    ->where('id',$v)
                                    ->find();
                                $orderId = Db::name('qt_order_project')->where('id',$v)->value('order_id');
                                if (empty($checkProjectOrder)) {
                                    //更新项目总订单
                                    Db::name('qt_order')->where('id',$orderId)->update([
                                        'pay_status' => 2,
                                        'pay_time' => time(),
                                    ]);
                                }
                            }
                        }
                    }
                }
                //判断房间是否还有未结账的商品子订单如果没有更新总订单
                foreach ($goodsOrderIds as $key=>$value){
                    $checkPGoodsOrder = Db::name('qt_product_order_item')
                        ->where([ 'pay_status' => '0'])
                        ->where('id',$value)
                        ->find();
                    if (empty($checkPGoodsOrder)) {
                        //更新项目总订单
                        $goodsOrder = Db::name('qt_product_order_item')
                            ->where('id',$value)
                            ->find();
                        Db::name('qt_product_order')->where('id', $goodsOrder['order_id'])->update([
                            'payment_price' => $totalGoodsPrice,
                            'order_status' => 1,
                            'pay_time' => time(),
                            'pay_status' => 1
                        ]);
                    }
                }
                //插入结算子表
                $subOrderInsert = array_merge($projectInsert, $goodsInsert);
                Db::name('qt_check_out_item')->insertAll($subOrderInsert);
                if(!empty($roomIds)){
                    foreach ($roomIds as $key=>$value){
                        //判断房间是否有技师
                        $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $value])->find();
                        //如果没有，更新房间状态
                        if (empty($engineerStatus)) {
                            //自动脏房
                            if ($this->storeInfo['is_auto_dirty_room'] == '1') {
                                Db::name('qt_room')->where('id', $value)->update(['status_id' => '5']);
                            }
                        }
                    }
                }
                if ($post['total_money'] == '0') {
                    if ($this->storeInfo['is_print_zero_order'] == '1') {
                        //调用结算打印
                        //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
                    }
                } else {
                    //调用结算打印
                    //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
                }
                $result = PrintService::printPcBill($checkOutId,$this->userInfo);
                //门店模式为鞋吧回收
                if($this->storeInfo['type'] == '4'){
                    if(!empty($handCardIds)){
                        foreach ($handCardIds as $key=>$value){
                            $this->recoveryHandCard($value,$this->userInfo);
                        }
                    }
                }
            }catch (Exception $exception){
                $this->result('结算失败，请稍后再试','',204);
            }
            $this->result('结算成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 使用会员卡支付发送短信
     */
    public function userCardSendSms(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['mobile'])){
                $this->result('缺少参数','',204);
            }
            $code = '123456';
            $sendSms = new Smscm();
            $result = $sendSms->sendsms($getData['mobile'],'你好，您的验证码是123456',3,$code);
            if($result == false){
                $this->result('短信发送失败','',204);
            }else{
                $this->result('短信发送成功','',200);
            }
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 获取用户房间单据
     */
    public function bill(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['room_id'])){
                $this->result('缺少参数','',204);
            }
            $where = [];
            //手牌号筛选
            if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                $handCardId = Db::name('qt_hand_card')->where('name',$getData['hand_card_name'])->value('id');
                $where[] = ['hand_card_id','=',$handCardId];
            }
            //技师号筛选
            if(isset($getData['work_number']) && !empty($getData['work_number'])){
                $engineerId = Db::name('qt_users')->where('work_number',$getData['work_number'])->value('id');
                $where[] = ['engineer_id','=',$engineerId];
            }
            //结账筛选
            if(isset($getData['pay_status']) && !empty($getData['pay_status'])){
                $where[] = ['pay_status','=',$getData['pay_status']];
            }
            //项目
            $project = Db::name('qt_order')
                ->field('o.id,r.name as room_name,h.name as hand_card_name')
                ->alias('o')
                ->leftJoin('qt_room r','r.id = o.room_id')
                ->leftJoin('qt_hand_card h','h.id = o.hand_card_id')
                ->where(['room_id'=>$getData['room_id'],'pay_status'=>'1'])
                ->order('o.id desc')
                ->find();
            $projectRes = Db::name('qt_order_project')
                ->field('id as product_order_id,name as goods_name,old_name as old_goods_name,order_type,created_time,engineer_id,start_time,end_time,old_card_id,hand_card_id,old_card_id,old_room_id,is_change,status,is_add,created_order_id as create_id,commission,receiver,sale_id,price')
                ->where('order_id',$project['id'])
                ->whereNotIn('status',['4','5'])
                ->whereNotNull('engineer_id')
                ->where($where)
                ->select();
            foreach ($projectRes as $key=>$value){
                $projectRes[$key]['work_number'] = Db::name('qt_users')->where('id',$value['engineer_id'])->value('work_number');//技师
                $projectRes[$key]['sale_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');//销售人
                $projectRes[$key]['room_name'] = $project['room_name'];
                $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id',$value['hand_card_id'])->value('name');
                $projectRes[$key]['old_card_name'] = Db::name('qt_hand_card')->where('id',$value['old_card_id'])->value('name');
                $projectRes[$key]['old_room'] = Db::name('qt_room')->where('id', $value['old_room_id'])->value('name');//原房间
                $projectRes[$key]['create_name'] = Db::name('qt_users')->where('id',$value['create_id'])->value('real_name');//下单人
                $projectRes[$key]['type'] = '1';//下单人
                $projectRes[$key]['goods_num'] = '1';//数量
            }
            //商品
            $goods = Db::name('qt_product_order')
                ->field('o.id,r.name as room_name,h.name as hand_card_name,engineer_id')
                ->alias('o')
                ->leftJoin('qt_room r','r.id = o.room_id')
                ->leftJoin('qt_hand_card h','h.id = o.hand_card_id')
                ->where(['room_id'=>$getData['room_id']])
                ->order('o.id desc')
                ->find();
            $productRes = Db::name('qt_product_order_item')
                ->field('id as product_order_id,goods_name,old_goods_name,old_goods_name,goods_num,create_time,create_id,sale_id,old_room_id,commission,receiver,goods_price as price')
                ->where('order_id',$goods['id'])
                ->where('pay_status','0')
                ->where($where)
                ->select();
            foreach ($productRes as $key=>$value) {
                $productRes[$key]['engineer_name'] = '';//提成
                $productRes[$key]['sale_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');//销售人
                $productRes[$key]['room_name'] = $goods['room_name'];
                $productRes[$key]['hand_card_name'] = '';
                $productRes[$key]['create_name'] = Db::name('qt_users')->where('id', $value['create_id'])->value('real_name');//提成
                $productRes[$key]['old_card_name'] = '';
                $productRes[$key]['status'] = 0;
                $productRes[$key]['is_change'] = '1';
                $productRes[$key]['is_add_work'] = 0;
                $productRes[$key]['order_type'] = '';
                $productRes[$key]['start_time'] = null;
                $productRes[$key]['end_time'] = null;
                $productRes[$key]['old_room'] = Db::name('qt_room')->where('id', $value['old_room_id'])->value('name');//原房间
                $productRes[$key]['type'] = '2';//商品
            }
            $data = array_merge($projectRes,$productRes);
            $this->result('请求成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 更换商品
     */
    public function changeGoods(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['goods_id']) || empty($getData['num']) || empty($getData['product_order_id'])){
                $this->result('缺少参数','',204);
            }
            $find = Db::name('qt_product_order_item')
                ->where(['id'=>$getData['product_order_id']])
                ->find();
            if(empty($find)){
                $this->result('当前商品订单不存在','',204);
            }
            if($find['pay_status'] == '1'){
                $this->result('已结算商品不支持修改','',204);
            }
            //构建新的项目
            $newProject = Db::name('qt_goods')->field('id,name,price')->where('id',$getData['goods_id'])->find();
            $updateData = [
                'old_goods_name'=>$find['goods_name'],
                'goods_name'=>$newProject['name'],
                'goods_price'=>$newProject['price'],
                'goods_total_price'=> bcmul($newProject['price'],$getData['num'],2),
                'goods_num'=> $getData['num'],
            ];
            try{
                //更新项目订单状态
                Db::name('qt_product_order_item')->where('id',$getData['product_order_id'])->update($updateData);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                $this->result('更换失败','',204);
            }
            $this->result('更换成功','',200);
        }
    }




    /**
     * 删除商品
     */
    public function delGoods(){

        if ($this->request->isPost()) {

            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if(empty($getData['product_order_id']) || empty($getData['type'])){
                $this->result('缺少参数','',204);
            }
            if($getData['type'] == '1'){
                $find = Db::name('qt_order_project')
                    ->where(['id'=>$getData['product_order_id']])
                    ->find();
                //退手牌总金额
                HandCardM::decHandCardMoney($find['id'],$find['hand_card_id'],'1');
                if(empty($find)){
                    $this->result('当前项目订单不存在','',204);
                }
                if($find['pay_status'] == '1'){
                    $this->result('已结算项目不允许删除','',204);
                }
                //不是加钟的情况下判断当天是否有加钟
                if($find['order_type'] != '5'){
                    //查找今天是否有加钟
                    $addFind = Db::name('qt_order_project')
                        ->where('order_id',$find['order_id'])
                        ->where(['order_type'=>'5','engineer_id'=>$find['engineer_id']])
                        ->find();
                    if(!empty($addFind)){
                        $this->result('当前技师有加钟项目，请先删除加钟项目','',204);
                    }
                }
                //技师在其他房间并且是上钟状态的不允许删除钟
                $engineerRes = Db::name('qt_users')->where('id',$find['engineer_id'])->value('work_status');
                $queue = Db::name('qt_order_queue')->where('user_id',$find['engineer_id'])->value('room_id');
                if($engineerRes == '4' && $queue != $find['room_id']){
                    $this->result('当前技师有加钟项目，请先删除加钟项目','',204);
                }
                //删除项目
                $del = Db::name('qt_order_project')->where('id',$getData['product_order_id'])->update(['is_delete'=>'1']);
                //判断房间是否有其他技师更新房间状态
                $roomQueue = Db::name('qt_order_queue')
                    ->where(['room_id'=>$find['room_id']])
                    ->where('user_id','!=',$find['engineer_id'])
                    ->find();
                //如果没有其他技师更新房间状态
                if(empty($roomQueue)){
                    Db::name('qt_room')->where('id',$find['room_id'])->update(['status'=>'10']);
                }else{
                    Db::name('qt_room')->where('id',$find['room_id'])->update(['status_id'=>$roomQueue['status']]);
                }
                /********** 先删除项目语音播报 ************/
                $find_room_name = Db::name('qt_room')->where('id', $find['room_id'])->value('name')?? '';
                $engineer_data = Db::name('qt_users')->where('id',$find['engineer_id'])->find();
                $text = $engineer_data['work_number'].'号  ' . $find_room_name . '  ' . $find['name'] . ' 取消';
                Db::name('qt_commission_log')->where(['type'=>'1','order_project_id'=>$getData['product_order_id']])->delete();
                Db::name('qt_send_voice_msg')->insert(['content' => $text, 'type' => 2,'create_time'=>time(),'voice_type'=>4]);
                /********** 查找当前技师是否在其他房间 ************/
                $engineer = Db::name('qt_order_queue')
                    ->where(['room_id'=>$find['room_id'],'user_id'=>$find['engineer_id']])
                    ->find();
                if(!empty($engineer)){
                    /********** 更改技师状态为空闲 ************/
                    Db::name('qt_users')->where('id',$find['engineer_id'])->update(['work_status'=>'1']);
                    Db::name('qt_order_queue')->where('user_id',$find['engineer_id'])
                        ->update([
                            'room_id'=>null,
                            'project_id'=>null,
                            'order_project_id'=>null,
                            'order_user_id'=>null,
                            'start_time'=>null,
                            'end_time'=>null,
                            'real_time'=>null,
                            'return_time'=>time(),
                            'status'=>'1'
                        ]);
                }
            }
            if($getData['type'] == '2'){
                $find = Db::name('qt_product_order_item')
                    ->where(['id'=>$getData['product_order_id']])
                    ->find();
                //退手牌总金额
                HandCardM::decHandCardMoney($find['id'],$find['hand_card_id'],'2');
                if(empty($find)){
                    $this->result('当前商品订单不存在','',204);
                }
                if($find['pay_status'] == '1'){
                    $this->result('已结算商品不允许删除','',204);
                }

                //写云大屏播放语音文本
                $order_item = Db::name('qt_product_order_item')
                    ->alias('oi')
                    ->field([
                        'oi.goods_name',
                        'oi.goods_num',
                        'oi.goods_total_price',
                        'po.room_id',
                        'po.engineer_id',
                        'r.name as room_name',
                    ])
                    ->leftJoin('qt_product_order po', 'po.id=oi.order_id')
                    ->leftJoin('qt_room r', 'po.room_id=r.id')
                    ->where('oi.store_id', $userInfo['store_id'])
                    ->where('oi.id', $getData['product_order_id'])
                    ->find();
                if (!empty($order_item)) {
                    $text = $order_item['room_name'] . '  ' . $order_item['goods_name']  . ' 退单';
                    Db::name('qt_send_voice_msg')->insert(['content' => $text, 'type' => 1,'create_time'=>time(),'voice_type'=>2]);
                }
                $del = Db::name('qt_product_order_item')->where('id',$getData['product_order_id'])->update(['status'=>'2']);
                Db::name('qt_commission_log')->where(['type'=>'2','order_project_id'=>$getData['product_order_id']])->delete();
            }
            if($del){
                $this->result('删除成功','',200);
            }
            $this->result('删除失败','',204);
        }
    }


    /**
     * 修改销售人
     */
    public function changeSale(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['product_order_id']) || empty($getData['sale_id'])  || empty($getData['type']) ){
                $this->result('缺少参数','',204);
            }
            if($getData['type'] == '1'){
                $find = Db::name('qt_order_project')
                    ->where(['id'=>$getData['product_order_id']])
                    ->find();
                if(empty($find)){
                    $this->result('当前项目订单不存在','',204);
                }
                $update = Db::name('qt_order_project')->where('id',$getData['product_order_id'])->update(['sale_id'=>$getData['sale_id']]);
                //更新提出成记录
                Db::name('qt_commission_log')->where('order_project_id',$getData['product_order_id'])->update(['user_id'=>$getData['sale_id']]);
            }
            if($getData['type'] == '2'){
                $find = Db::name('qt_product_order_item')
                    ->where(['id'=>$getData['product_order_id']])
                    ->find();
                if(empty($find)){
                    $this->result('当前商品订单不存在','',204);
                }
                $update = Db::name('qt_product_order_item')->where('id',$getData['product_order_id'])->update(['sale_id'=>$getData['sale_id']]);
                //更新提出成记录
                Db::name('qt_commission_log')->where('order_project_id',$getData['product_order_id'])->update(['cashier_id'=>$getData['sale_id']]);
            }
            if($update !== false){
                $this->result('修改成功','',200);
            }
            $this->result('修改失败','',204);
        }
    }


    /**
     * 修改提成
     */
    public function changeCommission(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['product_order_id'])  || empty($getData['type']) || empty($getData['money'])){
                $this->result('缺少参数','',204);
            }
            //项目
            if($getData['type'] == '1'){
                $find = Db::name('qt_order_project')
                    ->where(['id'=>$getData['product_order_id']])
                    ->find();
                if(empty($find)){
                    $this->result('当前商品项目不存在','',204);
                }
                $update = Db::name('qt_order_project')->where('id',$getData['product_order_id'])->update(['commission'=>$getData['money']]);
                //修改提成记录
                Db::name('qt_commission_log')
                    ->where(['type'=>'1','order_project_id'=>$getData['product_order_id']])
                    ->update(['receiver'=>$getData['money']]);
            }
            if($getData['type'] == '2'){
                $find = Db::name('qt_product_order_item')
                    ->where(['id'=>$getData['product_order_id']])
                    ->find();
                if(empty($find)){
                    $this->result('当前商品订单不存在','',204);
                }
                $update = Db::name('qt_product_order_item')->where('id',$getData['product_order_id'])->update(['receiver'=>$getData['money']]);
                //修改提成记录
                Db::name('qt_commission_log')->where(['type'=>'2','order_project_id'=>$getData['product_order_id']])->update(['commission'=>$getData['money']]);
            }
            if($update !== false){
                $this->result('修改成功','',200);
            }
            $this->result('删除失败','',204);
        }
    }


    /**
     * 修改上钟类型
     */
    public function  changeClock(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['product_order_id'])  || empty($getData['order_type'])){
                $this->result('缺少参数','',204);
            }
            //项目
            $find = Db::name('qt_order_project')
                ->where(['id'=>$getData['product_order_id']])
                ->find();
            if($find['order_type'] == $getData['order_type']){
                $this->result('更改上钟类型与原来一致','',204);
            }

            if(empty($find)){
                $this->result('当前项目订单不存在','',204);
            }
            //加钟不能改为其他类型
            if($find['order_type'] == '5'){
                $this->result('加钟不支持更改为其他类型','',204);
            }
            //其他类型不支持改为加钟
            if($getData['order_type'] == '5'){
                $this->result('不支持更改为加钟','',204);
            }
            $update = Db::name('qt_order_project')->where('id',$getData['product_order_id'])->update(['order_type'=>$getData['order_type']]);
            //如果是轮排改为加钟的话，并且技师为空闲状态，还原技师的顺序
            if($find['order_type'] == '1' && $getData['order_type'] == '2'){
                $engineerStatus = Db::name('qt_users')->where('id',$find['engineer_id'])->value('work_status');
                if($engineerStatus == '1'){
                    //技师状态为空闲时候还原技师顺序
                    $queue = Db::name('qt_order_queue')->where('user_id',$find['engineer_id'])->find();
                    Db::name('qt_order_queue')->where('user_id',$find['engineer_id'])->update(['sort'=>$queue['old_sort'],'old_sort'=>$queue['sort']]);
                }
            }
            //如果是轮排改为call钟的话，并且技师为空闲状态，还原技师的顺序
            if($find['order_type'] == '1' && $getData['order_type'] == '3'){
                $engineerStatus = Db::name('qt_users')->where('id',$find['engineer_id'])->value('work_status');
                if($engineerStatus == '1'){
                    //技师状态为空闲时候还原技师顺序
                    $queue = Db::name('qt_order_queue')->where('user_id',$find['engineer_id'])->find();
                    Db::name('qt_order_queue')->where('user_id',$find['engineer_id'])->update(['sort'=>$queue['old_sort'],'old_sort'=>$queue['sort']]);
                }
            }
            if($update !== false){
                $this->result('修改成功','',200);
            }
            $this->result('删除失败','',204);
        }
    }


    /**
     * 修改时间
     */
    public function changeTime(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['product_order_id'])  || empty($getData['time'])  || empty($getData['type'])){
                $this->result('缺少参数','',204);
            }
            //项目
            $find = Db::name('qt_order_project')
                ->where(['id'=>$getData['product_order_id']])
                ->find();
            if($getData['type'] == '1'){
                //提前
                $time = $find['start_time'] - ($getData['time'] * 60);
            }
            if($getData['type'] == '2'){
                //推迟
                $time = $find['start_time'] + ($getData['time'] * 60);
            }
            $update = Db::name('qt_order_project')->where('id',$getData['product_order_id'])->update(['start_time'=>$time]);
            //修改当前上钟的时间
            $orderQueue = Db::name('qt_order_queue')->where('user_id',$find['engineer_id'])->find();
            if(!empty($orderQueue['start_time']) && empty($orderQueue['end_time'])){
                Db::name('qt_order_queue')->where('user_id',$find['engineer_id'])->update(['start_time'=>$time]);
            }
            if($update !== false){
                $this->result('修改成功','',200);
            }
            $this->result('删除失败','',204);
        }
    }


    /**
     * 获取次卡详细内容
     */
    public function getNumberTemplate(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['viper_type_id'])){
                $this->result('缺少参数','',204);
            }
            static $couponData = [];
            $resultTemplate = [];
            $resultProject= [];
            $i = 0;
            if(!empty($getData['goods'])){
                //处理商品抵扣
                $goodsIds = explode(',',$getData['goods']);
                //查询缓存里面是否存在
                foreach ($goodsIds as $key=>$value){
                    $goodsRes = Db::name('qt_goods')->where('id',$value)->find();
                    $resultTemplate[$key]['product_name'] = $goodsRes['name'];
                    $template = Db::name('qt_viper_number_card_template_item')
                        ->field('t.id,t.expire,t.create_time')
                        ->alias('tt')
                        ->leftJoin('qt_viper_number_card_template t','t.id = tt.number_card_template_id')
                        ->where('tt.item_type','goods')
                        ->where('tt.item_id',$value)
                        ->where('t.viper_type_id',$getData['viper_type_id'])
                        ->group('viper_type_id')
                        ->select();
                    if(empty($template)){
                        //无抵扣次卡
                        $resultTemplate[$key]['product_id'] = 'goods-'.$value;//商品ID
                        $resultTemplate[$key]['id'] = '';//抵扣次卡模板ID
                        $resultTemplate[$key]['name'] = '';//抵扣次卡项目合集
                        $resultTemplate[$key]['num'] = '';//抵扣次卡数量
                        $resultTemplate[$key]['expire'] = '';//抵扣次卡有效期
                        $resultTemplate[$key]['price'] = $goodsRes['price'];
                    }else{
                        //有抵扣次卡
                        foreach ($template as $k=>$v){
                            $resultTemplate[$key]['id'] = $v['id'];//抵扣次卡模板ID
                            $data = Db::name('qt_viper_number_card_template_item')->where('number_card_template_id',$v['id'])->find();
                            //次卡包含的商品
                            $nameData = Db::name('qt_viper_number_card_template_item')
                                ->alias('item')
                                ->leftJoin('qt_goods g','g.id = item.item_id')
                                ->where('item.number_card_template_id',$v['id'])
                                ->where('item.item_type','goods')
                                ->column('g.name');
                            $resultTemplate[$key]['name'] = implode(',',$nameData);
                            $resultTemplate[$key]['num'] = '1';
                            $resultTemplate[$key]['expire'] = ($data['expire'] * 86400) + $v['create_time'];
                            $resultTemplate[$key]['price'] = $goodsRes['price'];
                            $resultTemplate[$key]['product_id'] = 'goods-'.$value;//商品ID
                            $couponData[$i]['id'] = $v['id'];
                            $couponData[$i]['name'] = implode(',',$nameData);
                            $couponData[$i]['expire'] = ($data['expire'] * 86400) + $v['create_time'];
                            $couponData[$i]['num'] = '1';
                            $i++;
                        }
                    }
                }
            }
            if(!empty($getData['project'])){
                //处理项目抵扣
                $projectIds = explode(',',$getData['project']);
                foreach ($projectIds as $key=>$value) {
                    $projectRes = Db::name('qt_project')->where('id', $value)->find();
                    $resultProject[$key]['product_name'] = $projectRes['name'];
                    $template = Db::name('qt_viper_number_card_template_item')
                        ->field('t.id,t.expire,t.create_time')
                        ->alias('tt')
                        ->leftJoin('qt_viper_number_card_template t', 't.id = tt.number_card_template_id')
                        ->where('tt.item_type', 'project')
                        ->where('tt.item_id', $value)
                        ->where('t.viper_type_id', $getData['viper_type_id'])
                        ->group('viper_type_id')
                        ->select();
                    if (empty($template)) {
                        //无抵扣次卡
                        $resultProject[$key]['product_id'] = 'project-'.$value;//项目ID
                        $resultProject[$key]['id'] = '';//抵扣次卡模板ID
                        $resultProject[$key]['name'] = '';//抵扣次卡项目合集
                        $resultProject[$key]['num'] = '';//抵扣次卡数量
                        $resultProject[$key]['expire'] = '';//抵扣次卡有效期
                        $resultProject[$key]['price'] = $projectRes['price'];//价格
                    } else {
                        //有抵扣次卡
                        foreach ($template as $k => $v) {
                            $resultProject[$key]['id'] = $v['id'];//抵扣次卡模板ID
                            $data = Db::name('qt_viper_number_card_template_item')->where('number_card_template_id', $v['id'])->find();
                            //次卡包含的项目
                            $dataName = Db::name('qt_viper_number_card_template_item')
                                ->alias('item')
                                ->leftJoin('qt_project p','p.id = item.item_id')
                                ->where('item.number_card_template_id',$v['id'])
                                ->where('item.item_type','project')
                                ->column('p.name');
                            $resultProject[$key]['product_id'] = 'project-'.$value;//项目ID
                            $resultProject[$key]['name'] = implode(',', $dataName);
                            $resultProject[$key]['num'] = '1';
                            $resultProject[$key]['expire'] = ($data['expire'] * 86400) + $data['create_time'];
                            $resultProject[$key]['price'] = $projectRes['price'];

                            $couponData[$i]['id'] = $v['id'];
                            $couponData[$i]['name'] = implode(',', $dataName);
                            $couponData[$i]['expire'] = ($data['expire'] * 86400) + $data['create_time'];
                            $couponData[$i]['num'] = '1';
                            $i++;
                        }
                    }
                }
            }
            $result = array_merge($resultTemplate,$resultProject);
            $couponData = unique_2d_array_by_key($couponData,'name');
            $newData ['coupon'] = $couponData;
            $newData ['result'] = $result;
            $this->result('查询成功',$newData,200);
        }
    }



    /**
     * 获取月卡详细内容
     */
    public function getMonthTemplate(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['viper_type_id'])){
                $this->result('缺少参数','',204);
            }
            static $couponData = [];
            $i = 0;
            //处理商品抵扣
            $goodsIds = explode(',',$getData['goods']);
            foreach ($goodsIds as $key=>$value){
                $goodsRes = Db::name('qt_goods')->where('id',$value)->find();
                $resultTemplate[$key]['product_name'] = $goodsRes['name'];
                $template = Db::name('qt_viper_month_card_template_item')
                    ->field('t.id,t.expire,t.create_time')
                    ->alias('tt')
                    ->leftJoin('qt_viper_month_card_template t','t.id = tt.month_template_id')
                    ->where('tt.item_type','goods')
                    ->where('tt.item_id',$value)
                    ->where('t.viper_type_id',$getData['viper_type_id'])
                    ->group('viper_type_id')
                    ->select();
                if(empty($template)){
                    //无抵扣月卡
                    $resultTemplate[$key]['product_id'] = 'goods-'.$value;//商品ID
                    $resultTemplate[$key]['id'] = '';//抵扣次卡模板ID
                    $resultTemplate[$key]['name'] = '';//抵扣次卡项目合集
                    $resultTemplate[$key]['num'] = '';//抵扣次卡数量
                    $resultTemplate[$key]['expire'] = '';//抵扣次卡有效期
                    $resultTemplate[$key]['price'] = $goodsRes['price'];
                }else{
                    //有抵扣月卡
                    foreach ($template as $k=>$v){
                        $resultTemplate[$key]['id'] = $v['id'];//抵扣次卡模板ID
                        $data = Db::name('qt_viper_month_card_template_item')->where('month_template_id',$v['id'])->find();
                        //月卡包含的商品
                        $nameData = Db::name('qt_viper_month_card_template_item')
                            ->alias('item')
                            ->leftJoin('qt_goods g','g.id = item.item_id')
                            ->where('item.number_card_template_id',$v['id'])
                            ->where('item.item_type','goods')
                            ->column('g.name');
                        $resultTemplate[$key]['product_id'] = 'goods-'.$value;//商品ID
                        $resultTemplate[$key]['name'] = implode(',',$nameData);
                        $resultTemplate[$key]['num'] = '1';
                        $resultTemplate[$key]['expire'] = $v['expire'];
                        $resultTemplate[$key]['price'] = $goodsRes['price'];
                        $couponData[$i]['name'] = implode(',',$nameData);
                        $couponData[$i]['expire'] = ($v['expire'] * 86400) + $v['create_time'];
                        $couponData[$i]['num'] = '1';
                        $i++;

                    }
                }
            }
            //处理项目抵扣
            $projectIds = explode(',',$getData['project']);
            foreach ($projectIds as $key=>$value) {
                $projectRes = Db::name('qt_project')->where('id', $value)->find();
                $resultProject[$key]['product_name'] = $projectRes['name'];
                $template = Db::name('qt_viper_month_card_template_item')
                    ->field('t.id,t.expire,t.create_time')
                    ->alias('tt')
                    ->leftJoin('qt_viper_month_card_template t', 't.id = tt.month_template_id')
                    ->where('tt.item_type', 'project')
                    ->where('tt.item_id', $value)
                    ->where('t.viper_type_id', $getData['viper_type_id'])
                    ->group('viper_type_id')
                    ->select();
                if (empty($template)) {
                    //无抵扣次卡
                    $resultProject[$key]['product_id'] = 'project-'.$value;//商品ID
                    $resultProject[$key]['id'] = '';//抵扣次卡模板ID
                    $resultProject[$key]['name'] = '';//抵扣次卡项目合集
                    $resultProject[$key]['num'] = '';//抵扣次卡数量
                    $resultProject[$key]['expire'] = '';//抵扣次卡有效期
                    $resultProject[$key]['price'] = $projectRes['price'];//价格
                } else {
                    //有抵扣次卡
                    foreach ($template as $k => $v) {
                        $resultProject[$key]['id'] = $v['id'];//抵扣次卡模板ID
                        //月卡包含的项目
                        $dataName = Db::name('qt_viper_month_card_template_item')
                            ->alias('item')
                            ->leftJoin('qt_project p','p.id = item.item_id')
                            ->where('item.month_template_id',$v['id'])
                            ->where('item.item_type','project')
                            ->column('p.name');
                        $resultProject[$key]['product_id'] = 'project-'.$value;//商品ID
                        $resultProject[$key]['name'] = implode(',', $dataName);
                        $resultProject[$key]['num'] = '1';
                        $resultProject[$key]['expire'] = ($v['expire'] * 86400) + $v['create_time'];
                        $resultProject[$key]['price'] = $projectRes['price'];
                        $couponData[$i]['name'] = implode(',', $dataName);
                        $couponData[$i]['expire'] = ($v['expire'] * 86400) + $v['create_time'];
                        $couponData[$i]['num'] = '1';
                        $i++;
                    }
                }
            }
            $result = array_merge($resultTemplate,$resultProject);
            $couponData = unique_2d_array_by_key($couponData,'name');
            $newData ['coupon'] = $couponData;
            $newData ['result'] = $result;
            $this->result('查询成功',$newData,200);
        }
    }



    /**
     * 会员卡支付
     * @param $data
     */
    public function pay_card($data,$checkOutId){
       // [{"id":10,"amount":10,"give_amount":100,"template_id":'1'}]
        $viperCard  = Db::name('qt_viper_card')->where(['id'=>$data['id']])->find();
        if(empty($viperCard)){
            $this->result('暂未找到该会员卡','',204);
        }
        if($viperCard['amount'] < $data['pay_amount']){
            $this->result('会员卡余额不足','',204);
        }
        if($viperCard['give_amount'] < $data['pay_give_amount']){
            $this->result('会员卡赠送余额不足','',204);
        }
        try{
            //更新会员卡
            Db::name('qt_viper_card')->where('id',$viperCard['id'])->setDec('amount',$data['pay_amount']);
            Db::name('qt_viper_card')->where('id',$viperCard['id'])->setDec('give_amount',$data['pay_give_amount']);
            //插入会员消费记录
            $after = $viperCard['amount'] - $data['pay_amount'];
            $log[0] = [
                'viper_card_id'=>$viperCard['id'],
                'chock_order_id'=>$checkOutId,
                'type'=>'3',
                'money'=>$data['pay_amount'],
                'create_time'=>time(),
                'content'=>'',
                'check'=>'2',
                'flag'=>'1',
                'after_money'=>$after,
            ];
            if(!empty($data['pay_give_amount'])){
                $log[1] = [
                    'viper_card_id'=>$viperCard['id'],
                    'type'=>'3',
                    'chock_order_id'=>$checkOutId,
                    'money'=>$data['pay_amount'],
                    'create_time'=>time(),
                    'content'=>'',
                    'check'=>'2',
                    'flag'=>'3',
                    'after_money'=>$after,
                ];
            }
            Db::name('qt_viper_money_log')->insertAll($log);
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            $this->result('消费失败','',204);
        }
    }

    /**
     * 处理次卡消费
     * @param $data [会员卡消费数据]
     * @param $checkOutID [结账单据ID]
     */
    public function pay_number_card($data,$checkOutID){
        //查询会员次卡信息

        $viperUser = Db::name('qt_viper_card')
            ->field('id,store_id')
            ->where('id',$data['id'])
            ->find();
        foreach ($data['template_data'] as $key=>$value){
            $number = Db::name('qt_viper_number_card_template_item')->where(['number_card_template_id'=>$value['template_id']])->value('number');
            $userUseNumber = Db::name('qt_viper_card_use_log')->where(['card_type'=>'1','viper_card_id'=>$data['id'],'template_id'=>$value['template_id']])->sum('number');
            $userUseNumber = intval($userUseNumber);
            if(($userUseNumber + 1) > $number){
                $this->result('会员卡超出使用数量','',204);
            }
            $product = explode('-',$value['product_id']);
            //插入会员卡使用记录
            $insert = [
                'user_id'=>$viperUser['id'],
                'store_id'=>$viperUser['store_id'],
                'viper_card_id'=>$data['id'],
                'template_id'=>$value['template_id'],
                'order_id'=>$checkOutID,
                'item_type'=>$product[0],
                'item_id'=>$product[1],
                'number'=>$value['num'],
                'create_time'=>time(),
                'card_type'=>'1',
                'card_item_id'=>$value['card_item_id'],
            ];
            Db::name('qt_viper_card_use_log')->insert($insert);
        }

    }


    /**
     * 处理月卡消费
     * @param $data
     */
    public function pay_month_card($data,$checkOutID){
        //查询会员月卡信息
        $viperUser = Db::name('qt_viper_card')
            ->field('id,store_id')
            ->where('id',$data['id'])
            ->find();
        foreach ($data['template_data'] as $key=>$value){
            $template = Db::name('qt_viper_month_card_template')->where('id',$value['template_id'])->find();
            $userMonthStatus = Db::name('qt_viper_card_item')
                ->where(['viper_card_id'=>$value['id'],'month_template_id'=>$value['template_id'],'status'=>'1'])
                ->find();
            if(empty($userMonthStatus)){
                $this->result('该月卡已经禁止使用','',204);
            }
            if($template['type'] == '1'){
                //每天
                $userUseNumber = Db::name('qt_viper_card_use_log')
                    ->where(['card_type'=>'2','viper_card_id'=>$value['id'],'template_id'=>$value['template_id']])
                    ->whereTime('create_time','today')
                    ->sum('number');
                if(($userUseNumber + 1) > $template['hz']){
                    $this->result('会员卡超出使用频率','',204);
                }
            }
            if($template['type'] == '2'){
                //每月
                $userUseNumber = Db::name('qt_viper_card_use_log')
                    ->where(['card_type'=>'2','viper_card_id'=>$value['id'],'template_id'=>$value['template_id']])
                    ->whereTime('create_time','m')
                    ->sum('number');
                if(($userUseNumber + 1) > $template['hz']){
                    $this->result('会员卡超出使用频率','',204);
                }
            }
            if($template['type'] == '3'){
                //每年
                $userUseNumber = Db::name('qt_viper_card_use_log')
                    ->where(['card_type'=>'2','viper_card_id'=>$value['id'],'template_id'=>$value['template_id']])
                    ->whereTime('create_time','y')
                    ->sum('number');
                if(($userUseNumber + 1) > $template['hz']){
                    $this->result('会员卡超出使用频率','',204);
                }
            }
            $product = explode('-',$value['product_id']);
            //插入会员卡使用记录
            $insert = [
                'user_id'=>$viperUser['id'],
                'store_id'=>$viperUser['store_id'],
                'viper_card_id'=>$data['id'],
                'template_id'=>$value['template_id'],
                'order_id'=>$checkOutID,
                'item_type'=>$product[0],
                'item_id'=>$product[1],
                'number'=>$value['num'],
                'create_time'=>time(),
                'card_type'=>$value['card_type'],
                'card_item_id'=>$value['card_item_id'],
            ];
            Db::name('qt_viper_card_use_log')->insert($insert);
        }



    }

    /**
     * 验证会员卡
     * @param $type [类型] [1密码，2验证码]
     * @param $code [密码或者验证码]
     * @param $cardId [会员卡ID]
     */
    public function checkPass($passwd,$code,$cardId){
        $cardRes = Db::name('qt_viper_card')->field('id,passwd')->where('id',$cardId)->find();
        if(!empty($passwd)){
            $newPass = pwd($code,$cardRes['salt']);
            if($newPass != $cardRes['passwd']){
                $this->result('密码错误','',204);
            }
        }elseif(!empty($code)){
            $sms = new Smscm();
            $result = $sms->check_smscode($cardRes['mobile'],$code,'3');
            if($result['code'] != '200'){
                $this->result('验证码错误','',204);
            }
        }
    }


    /**
     * 获取会员卡支付比例
     */
    public function viperCardDiscount(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['viper_type_id'])){
                $this->result('缺少参数','',204);
            }
            $data = Db::name('qt_viper_type')->field('id,amount_percentage,give_amount_percentage')->where('id',$getData['viper_type_id'])->find();
            $this->result('查询成功',$data,200);
        }
    }


    /**
     * 获取房间项目
     */
    public function project(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['room_id'])){
                $this->result('缺少参数','',204);
            }
            //项目
            $project = Db::name('qt_order')
                ->field('o.id,r.name as room_name,h.name as hand_card_name')
                ->alias('o')
                ->leftJoin('qt_room r','r.id = o.room_id')
                ->leftJoin('qt_hand_card h','h.id = o.hand_card_id')
                ->where(['room_id'=>$getData['room_id'],'pay_status'=>'1'])
                ->order('o.id desc')
                ->find();
            $projectRes = Db::name('qt_order_project')
                ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,status,start_time,real_end_time,created_order_id')
                ->where('order_id',$project['id'])
                ->where('is_change','1')
                ->select();
            foreach ($projectRes as $key=>$value){
                $projectRes[$key]['order_id'] = $project['id'];
                $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id',$value['engineer_id'])->value('work_number');
                $projectRes[$key]['room_name'] = $project['room_name'];
                $projectRes[$key]['hand_card_name'] = $project['hand_card_name'];
                $projectRes[$key]['create_name'] = Db::name('qt_users')->where('id',$value['created_order_id'])->value('real_name');
            }
            $this->result('查询成功',$projectRes,200);
        }
    }


    /**
     * 计算折扣
     */
    public function discount()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['active_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $result  = Discount::getDiscount($getData);
            $this->result($result['msg'], $result['data'], $result['code']);
        }
    }

    /**
     * 查询套餐费用
     */
    public static function package($orderProjectData,$goodsOrderData){
        //处理项目
        $key = array_column($orderProjectData,'project_id');
        array_multisort($key,SORT_ASC,$orderProjectData);
        $project = [];
        foreach ($orderProjectData as $key=>$value){
            $project[$key]= $value['project_id'].'-project-'.'1';
        }
        //处理商品
        $key = array_column($goodsOrderData,'goods_id');
        array_multisort($key,SORT_ASC,$goodsOrderData);
        $goods = [];
        foreach ($goodsOrderData as $key=>$value){
            $goods[$key]= $value['goods_id'].'-goods-'.$value['goods_num'];
        }
        $stringData = array_merge($project,$goods);
        $string = implode(',',$stringData);
        return $string;

    }

    //支付生成结账单
    public function room_pay (){

        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['room_id']) || empty($getData['pay_type'])){
                $this->result('缺少参数','',204);
            }
            if(!isset($getData['project_order_total_id'])){
                $getData['project_order_total_id'] = '';
            }
            if(!isset($getData['goods_order_total_id']) || empty($getData['goods_order_total_id'])){
                $getData['goods_order_total_id'] = '';
            }
            //备注默认为空
            if(!isset($getData['content']) || empty($getData['content'])){
                $getData['content'] = '';
            }
            if(!isset($getData['activity_id']) || empty($getData['activity_id'])){
                $getData['activity_id'] = '';
            }
            if(!isset($getData['cashier_remarks']) || empty($getData['cashier_remarks'])){
                $getData['cashier_remarks'] = '';
            }
            //构建主结算订单
            $checkOutInsert =[
                'store_id'=>$this->userInfo['store_id'],
                //'engineer_ids' => $getData['engineer_ids'],
                //'project_ids' => $getData['project_ids'],
                'order_no'=>check_order_sn(),
                'project_order'=>$getData['project_order_total_id'],
                'goods_order'=>$getData['goods_order_total_id'],
                'total_money'=>$getData['total_money'],
                'payment_money'=>$getData['payment_money'],
                'cashier_id'=>$this->userInfo['id'],
                'cashier_time'=>time(),
                'activity_id'=>$getData['activity_id'],
                'cashier_remarks'=>$getData['cashier_remarks'],
            ];
            $checkOutId = Db::name('qt_check_out')->insertGetId($checkOutInsert);
            //项目计算
            $projectRes = json_decode($getData['project'],true);
            $projectInsert = [];
            foreach ($projectRes as $key=>$value){
                $projectInsert[$key] = [
                    'activity_id'=>$getData['activity_id'],
                    'link_id'=>$value['project_id'],
                    'link_type'=>'1',
                    'check_out_id'=>$checkOutId,
                    'receivable'=>$value['payment_price'],
                ];
            }
            //商品数据插入
            $goodsRes = json_decode($getData['goods'],true);
            if(empty($goodsRes)){
                $goodsInsert = [];
            }
            foreach ($goodsRes as $key=>$value){
                $goodsInsert[$key] = [
                    'activity_id'=>$getData['activity_id'],
                    'link_id'=>$value['goods_id'],
                    'link_type'=>'2',
                    'check_out_id'=>$checkOutId,
                    'receivable'=>$value['payment_price'],
                ];
            }
            //插入结算子表
            $subOrderInsert = array_merge($projectInsert,$goodsInsert);
            Db::name('qt_check_out_item')->insertAll($subOrderInsert);
            //结账单号
            $checkOutOrder = Db::name('qt_check_out')->where(['id'=>$checkOutId])->value('order_no');
            $result = [];
            if($getData['pay_type'] == 'ALIPAY'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'ALIPAY',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $checkOutOrder,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }elseif($getData['pay_type'] == 'WECHAT'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'WECHAT',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $checkOutOrder,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }else{
                //会员卡结账
                $cardData = json_decode($getData['card_data'],true);
                $pay_card = RoomCheckOutService::payCard($cardData[0], $checkOutId,$this->userInfo);
                if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                    $this->result($pay_card['msg'], '', 204);
                }
            }
            //调用结算打印
            //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
            $result['check_out_id'] = $checkOutId;
            $this->result('结算成功',$result,200);
        }
        $this->result('无效的请求','',204);

    }


    /**
     * 前台支付回调查看支付状态
     */
    public function room_pay_notify(){

        if($this->request->isPost()) {
            $post = $this->request->post();
            $check_out_data = Db::name('qt_check_out')
                ->where(['id'=>$post['check_out_id']])
                ->value('pay_status');
            if (empty($check_out_data)) {
                $this->result('结账单ID没有找到对应的数据','',204);
            }
            $this->result('查询成功',$check_out_data,200);
        }
        $this->result('无效的请求','',204);

    }


    /**
     * 结账刷新二维码
     * @return void
     */
    public function room_pay_refresh(){
        if($this->request->isPost()) {
            $post = $this->request->post();
            //结账单号
            $orderNo = check_order_sn();
            $result = [];
            if($post['pay_type'] == 'ALIPAY'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'ALIPAY',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $orderNo,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }elseif($post['pay_type'] == 'WECHAT'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'WECHAT',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $orderNo,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }
            Db::name('qt_check_out')->where(['id'=>$post['check_out_id']])->update(['order_no'=>$orderNo]);
            $result['check_out_id'] = $post['check_out_id'];
            $this->result('查询成功',$result,200);

        }

    }


    /**
     * 计算会员价格
     */
    public function vip_discount()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $result  = Discount::getVipDiscount($getData);
            $this->result($result['msg'], $result['data'], $result['code']);
        }
    }



    /**
     * 回收手牌
     */
    public function  recoveryHandCard($handCardId,$userInfo)
    {
        //查询是否有未结账的商品和项目
        $projectOrder = Db::name('qt_order_project')->where(['hand_card_id'=>$handCardId,'pay_status'=>'0'])->find();
        $goodsOrder = Db::name('qt_product_order_item')->where(['hand_card_id'=>$handCardId,'pay_status'=>'0'])->find();
        if($projectOrder == null && $goodsOrder == null){
            $update = [
                'status'=>'3',
                'update_time'=>time(),
                'recovery_id'=>$userInfo['id']
            ];
            try{
                Db::startTrans();
                //修改订单状态
                Db::name('qt_hand_card')->where(['id'=>$handCardId])->update(['status'=>'1']);
                Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCardId])->order('id desc')->update($update);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
            }
        }
    }




}
